package org.webby.mappers;

import org.webby.RequestHandler;
import org.webby.RequestMapper;
import org.webby.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: samp
 * Date: Apr 20, 2007
 * Time: 5:50:03 PM
 * To change this template use File | Settings | File Templates.
 */
public class PatternRequestMapper implements RequestMapper {

  private Map<PatternMap, RequestHandler> maps = new TreeMap<PatternMap, RequestHandler>();

  public RequestMapping mapRequest(HttpServletRequest request) {
    String uri = request.getRequestURI();
    uri = uri.substring(request.getContextPath().length());
    for (PatternMap map : maps.keySet()) {
      for (Pattern pattern : map.getPatterns()) {
        Matcher matcher = pattern.matcher(uri);
        if (matcher.matches()) {
          Map<String, String> urlParamMap = new HashMap<String, String>();
          for (Attribute attribute : map.getAttributes()) {
            String value = attribute.getValue();
            urlParamMap.put(attribute.getName(), value != null ? value : matcher.group(attribute.getGroup()));
          }
          return new RequestMapping(maps.get(map), urlParamMap);
        }
      }
    }
    return null;
  }

  public void addMapping(PatternMap map, RequestHandler handler) {
    maps.put(map, handler);
  }

  public void addMapping(String map, RequestHandler handler) {
    maps.put(new PatternMap(map), handler);
  }
}
